package appx.craft.droid.ui;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;
import appx.craft.droid.R;
import appx.craft.droid.bean.JSONParams;
import appx.craft.droid.utils.Const;
import appx.craft.droid.utils.Log;
import appx.craft.droid.utils.Pref;
import appx.craft.droid.utils.Utility;

public class InputScreenActivity extends FragmentActivity implements
		android.view.View.OnClickListener {

	public final String TAG = InputScreenActivity.class.getCanonicalName();

	/**
	 * REQUEST CODE OF IMAGE GALLRY
	 */
	static final int RESULT_LOAD_IMAGE = 1;
	
	/**
	 * REQUEST CODE FOR AUDIO 
	 */
	static final int RESULT_LOAD_AUDIO = 2;
	
	/**
	 *  REQUEST CODE FOR VIDEO
	 */
	static int RESULT_VIDEO_CAPTURED = 3;
	
	Handler mHandler = new Handler();
	Button btn_send_image, btn_send_location, btn_send_video, btn_send_audio;
	ProgressBar progressBar_Upload;
	ImageView imageview_feedback_ok;
	Button btn_View, btn_resend;
	
	String imageUploadFileNam;
	String audioUploadFileNam;
	String videoUploadFileNam;
	Uri fileUri;
	
	String imageRetryFilePath;
	String audioRetryFilePath;
	
	ProgressDialog mProgressDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.debug(TAG, "[ onCreate ] ");
		Const.CONTEXT = InputScreenActivity.this;
		setContentView(R.layout.activity_input_screen);
		
		mProgressDialog = new ProgressDialog(InputScreenActivity.this);
		mProgressDialog.setIndeterminate(true);
		mProgressDialog.setCancelable(false);

		btn_send_image = (Button) findViewById(R.id.btn_send_image);
		btn_send_image.setOnClickListener(this);
		btn_send_location = (Button) findViewById(R.id.btn_send_location);
		btn_send_location.setOnClickListener(this);
		btn_send_video = (Button) findViewById(R.id.btn_send_video);
		btn_send_video.setOnClickListener(this);
		btn_send_audio = (Button) findViewById(R.id.btn_send_audio);
		btn_send_audio.setOnClickListener(this);

		btn_View = (Button) findViewById(R.id.btn_View);
		btn_View.setOnClickListener(this);
		btn_View.setVisibility(View.INVISIBLE);

		btn_resend = (Button) findViewById(R.id.btn_resend);
		btn_resend.setOnClickListener(this);
		btn_resend.setVisibility(View.INVISIBLE);

		imageview_feedback_ok = (ImageView) findViewById(R.id.imageview_feedback_ok);
		imageview_feedback_ok.setVisibility(View.INVISIBLE);

		progressBar_Upload = (ProgressBar) findViewById(R.id.progressBar_Upload);

	}

	/**
	 * All Activity that start for activity result we hold here
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		/** IF IMAGE RESULT **/
		if (requestCode == RESULT_LOAD_IMAGE) {
			
			if (resultCode == RESULT_OK) {
				
				if (data != null) {
					
					/** IF ALL OK THEN GET PATH OF IMAGE **/
					Uri selectedImage = data.getData();
					String[] filePathColumn = { MediaStore.Images.Media.DATA };

					Cursor cursor = getContentResolver().query(selectedImage,
							filePathColumn, null, null, null);
					cursor.moveToFirst();

					int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
					final String picturePath = cursor.getString(columnIndex);
					cursor.close();
					
					if(picturePath.endsWith(".PNG") || picturePath.endsWith(".JPEG") || picturePath.endsWith(".jpeg") || picturePath.endsWith(".jpg") || picturePath.endsWith(".JPG") || picturePath.endsWith(".png")){
							
						imageRetryFilePath = picturePath;
						// start upload image here
						new AsyncTask<Void, Void, Boolean>(){
							String mImageBase64;
							protected void onPreExecute() {
								mProgressDialog.setMessage("Please wait it start uploading.....");
								mProgressDialog.show();
							};
							
							@Override
							protected Boolean doInBackground(Void... params) {
								boolean result = false;
								try{
									
									Thread mThread = new Thread(new  Runnable() {
										
										@Override
										public void run() {
											mImageBase64 = Utility.imageEncodeTobase64(BitmapFactory.decodeFile(picturePath));
										}
									});
									mThread.start();
									
									mThread.join(2000);
									
								}catch (Exception e) {
									e.printStackTrace();
								}
								
								result = true;
								return result;
							}
							@Override
							protected void onPostExecute(Boolean result) {
								mProgressDialog.dismiss();
								
								if(result){
									if(mImageBase64 != null){
										
										if(Utility.isOnline()){
											new UploadImageTask().execute("2",mImageBase64);
										}
										else{
											Toast.makeText(getApplicationContext(),"Please check internet connection !!!",1000*1).show();
										}
											
									}
										
								}
								
							}
						}.execute();
					}
					
				}
				
			} else if (resultCode == RESULT_CANCELED) {
				Toast.makeText(getApplicationContext(),"Result canceled !!!",1000*1).show();
			}
			
			
		}
		/** For Audio capture **/
		else if(requestCode == RESULT_LOAD_AUDIO){
			
			if(resultCode == RESULT_OK){
				if(data!=null){
					
					Toast.makeText(getApplicationContext(),data.getExtras().getString("PATH"),1000*1).show();
					audioRetryFilePath = data.getExtras().getString("PATH");
					
					new AsyncTask<Void, Void, Boolean>(){
						String strAudioBase64;	
						protected void onPreExecute() {
							mProgressDialog.setMessage("Please wait it start uploading audio.....");
							mProgressDialog.show();
						};
						
						@Override
						protected Boolean doInBackground(Void... params) {
							boolean result = false;
							try{
								
								Thread mThread = new Thread(new  Runnable() {
									
									@Override
									public void run() {
										strAudioBase64 = Utility.encodeFileToBase64Binary(data.getExtras().getString("PATH"));
									}
								});
								mThread.start();
								
								mThread.join(2000);
								
							}catch (Exception e) {
								e.printStackTrace();
							}
							
							result = true;
							return result;
						}
						@Override
						protected void onPostExecute(Boolean result) {
							mProgressDialog.dismiss();
							if(result){
								new UploadAudioTask().execute("2",strAudioBase64);
							}
							
						}
					}.execute();
					
					
					
				}
				 
			}else if(resultCode == RESULT_CANCELED){
				Toast.makeText(getApplicationContext(),"Result canceled !!!",1000*1).show();
			}
			
		}else if(requestCode == RESULT_VIDEO_CAPTURED){
			
			if(resultCode == RESULT_OK){
				
				fileUri = data.getData();
				Toast.makeText(InputScreenActivity.this,getRealPathFromURI(fileUri),Toast.LENGTH_LONG).show();
				videoUploadFileNam = getRealPathFromURI(fileUri);
				if(Utility.isOnline()){
					new UploadVideoTask().execute("2",videoUploadFileNam);	
				}else{
					Toast.makeText(getApplicationContext(),"Please check internet connection!!.",1000*1).show();
				}
			}
		}

	}
	
	
	public String getRealPathFromURI(Uri contentUri) {
	    String[] proj = { MediaStore.Images.Media.DATA };
	    Cursor cursor = managedQuery(contentUri, proj, null, null, null);
	    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
	    cursor.moveToFirst();
	    return cursor.getString(column_index);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.activity_input_screen, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		default:
			return super.onOptionsItemSelected(item);
		}

	}

	@Override
	protected void onStart() {
		super.onStart();
		Log.debug(TAG, "[ onStart ] ");
	}

	@Override
	protected void onStop() {
		super.onStop();
		Log.debug(TAG, "[ onStop ] ");
	}

	@Override
	protected void onPause() {
		super.onPause();
		Log.debug(TAG, "[ onPause ] ");
	}

	@Override
	protected void onResume() {
		super.onResume();
		Log.debug(TAG, "[ onResume ] ");
		/**
		 * show welcome dialog
		 */
	//	showAlertDialog("Welcome Back");
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		Log.debug(TAG, "[ onDestroy ] ");
	}

	private void showAlertDialog(String title) {

		final AlertDialog mAlert$Welcome;
		final AlertDialog.Builder mBuilder$Alert = new AlertDialog.Builder(
				InputScreenActivity.this);

		mBuilder$Alert.setTitle(getResources().getString(R.string.app_name));
		mBuilder$Alert.setIcon(getResources().getDrawable(
				android.R.drawable.ic_dialog_info));
		mBuilder$Alert.setMessage(title);
		mBuilder$Alert.setPositiveButton("Dismiss", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
			}
		});
		mAlert$Welcome = mBuilder$Alert.create();
		mAlert$Welcome.show();
	}

	@Override
	public void onClick(View v) {
		int mBtnID = v.getId();

		cleanUploadView();

		if (mBtnID == R.id.btn_send_image) {
			
//			Intent intent = new Intent();
//			intent.setType("image/*");
//			intent.setAction(Intent.ACTION_GET_CONTENT);
//			intent.addCategory(Intent.CATEGORY_OPENABLE);
//			startActivityForResult(Intent.createChooser(intent, "Select Picture"), RESULT_LOAD_IMAGE);
			
			
			openCustomIntent(RESULT_LOAD_IMAGE,"image/*");
			

		} else if (mBtnID == R.id.btn_send_location) {
			
			
			if (Utility.isOnline()) {
				Toast.makeText(getApplicationContext(),"Loaction sending.....",1000*1).show();
				new sendLocationTask().execute("2");
			} else {
				showAlertDialog("Please check internet connection !!!");
			}
			
			
		} else if (mBtnID == R.id.btn_send_video) {
			
//			Intent intent = new Intent();
//			intent.setType("video/*");
//			intent.setAction(Intent.ACTION_GET_CONTENT);
//			startActivityForResult(Intent.createChooser(intent, "Select video"), RESULT_VIDEO_CAPTURED);
			
			openCustomIntent(RESULT_VIDEO_CAPTURED,"video/*");
			
			
		} else if (mBtnID == R.id.btn_send_audio) {
			
			/**
			 * start audio capture 
			 */
			Intent intent =  new Intent(InputScreenActivity.this,AudioRecordActivity.class);
			intent.putExtra(Const.INTENT_AUDIO,"false");
			startActivityForResult(intent, RESULT_LOAD_AUDIO);

		} else if (mBtnID == R.id.btn_View) {

			if (v instanceof Button) {
				String mTag = v.getTag().toString();
				if (mTag == "1") {
					// for image view
					if (Utility.isOnline()) {
						Intent mIntent = new Intent(InputScreenActivity.this,ImageViewActivity.class);
						mIntent.putExtra(Const.INTENT_IMAGE,imageUploadFileNam);
						startActivity(mIntent);
					}
					
				} else if (mTag == "2") {
					// Map view
					startActivity(new Intent(InputScreenActivity.this,
							CurrentLocation.class));

				} else if (mTag == "3") {
					// send video
					Intent intent =  new Intent(InputScreenActivity.this,VideoPreview.class);
					intent.putExtra(Const.INTENT_FILE_VIDEO,videoUploadFileNam);
					startActivity(intent);

				} else if (mTag == "4") {
					
					// view audio file 
					Intent intent =  new Intent(InputScreenActivity.this,AudioRecordActivity.class);
					intent.putExtra(Const.INTENT_AUDIO,"true");
					intent.putExtra(Const.INTENT_FILE_AUDIO,audioUploadFileNam);
					startActivityForResult(intent, RESULT_LOAD_AUDIO);

				}
			}
		}else if(mBtnID == R.id.btn_resend){
			
			if (v instanceof Button) {
				
				String mTag = v.getTag().toString();
				if (mTag == "1") {
					// for image view
					new AsyncTask<Void, Void, Boolean>(){
						String mImageBase64;
						protected void onPreExecute() {
							Toast.makeText(getApplicationContext(),"Please wait it start uploading.....",1000*1).show();
						};
						
						@Override
						protected Boolean doInBackground(Void... params) {
							boolean result = false;
							try{
								
								Thread mThread = new Thread(new  Runnable() {
									
									@Override
									public void run() {
										mImageBase64 = Utility.imageEncodeTobase64(BitmapFactory.decodeFile(imageRetryFilePath));
									}
								});
								mThread.start();
								
								mThread.join(2000);
								
							}catch (Exception e) {
								e.printStackTrace();
							}
							
							result = true;
							return result;
						}
						@Override
						protected void onPostExecute(Boolean result) {
							if(result){
								if(mImageBase64 != null){
									new UploadImageTask().execute("1",mImageBase64);	
								}
									
							}
							
						}
					}.execute();
					
				} else if (mTag == "2") {
					// Map view
					if (Utility.isOnline()) {
						Toast.makeText(getApplicationContext(),"Loaction sending.....",1000*1).show();
						new sendLocationTask().execute("1");
					} else {
						showAlertDialog("Please check internet connection !!!");
					}
					
				} else if (mTag == "3") {
					// send video
					if(Utility.isOnline()){
						new UploadVideoTask().execute("1",videoUploadFileNam);	
					}else{
						Toast.makeText(getApplicationContext(),"Please check internet connection!!.",1000*1).show();
					}
					
				} else if (mTag == "4") {
					// view audio file 
					new AsyncTask<Void, Void, Boolean>(){
						String strAudioBase64;	
						protected void onPreExecute() {
							mProgressDialog.setMessage("Please wait it start uploading audio.....");
							mProgressDialog.show();
						};
						
						@Override
						protected Boolean doInBackground(Void... params) {
							boolean result = false;
							try{
								
								Thread mThread = new Thread(new  Runnable() {
									
									@Override
									public void run() {
										strAudioBase64 = Utility.encodeFileToBase64Binary(audioRetryFilePath);
									}
								});
								mThread.start();
								
								mThread.join(2000);
								
							}catch (Exception e) {
								e.printStackTrace();
							}
							
							result = true;
							return result;
						}
						@Override
						protected void onPostExecute(Boolean result) {
							mProgressDialog.dismiss();
							if(result){
								new UploadAudioTask().execute("1",strAudioBase64);
							}
							
						}
					}.execute();
					
					
				}
				
			}
			
		}
	}

	/**
	 * SEND LOCATION OVER SERVER
	 * 
	 * @author BHAVDIP
	 * 
	 */
	private class sendLocationTask extends AsyncTask<String, String, Boolean> {
		
		boolean temp = false;
		boolean result = false;
		int mProgressStatus = 0;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			result = false;
		}

		@Override
		protected Boolean doInBackground(String... params) {
			try {

				new Thread(new Runnable() {
					public void run() {
						
						while (!result) {

							mProgressStatus = mProgressStatus + 1;
							if (mProgressStatus < 100) {
								try {
									Thread.sleep(210);
								} catch (InterruptedException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
								publishProgress(String.valueOf(mProgressStatus));
							}

						}

						if (result) {
							publishProgress(String.valueOf(100));
						}
					}
				}).start();

				InputStream is = null;
				JSONObject mobj$Json = null;
				String json = "";

				ArrayList<JSONParams> mArrayParams;
				JSONParams mObj$Params;

				mArrayParams = new ArrayList<JSONParams>();


				mObj$Params = new JSONParams();
				mObj$Params.setStr$Key(Const.PARAMS_RETRY);
				mObj$Params.setStr$value(params[0]);
				mArrayParams.add(mObj$Params);

				
				mObj$Params = new JSONParams();
				mObj$Params.setStr$Key(Const.PARAMS_LATITUDE);
				mObj$Params.setStr$value(Pref.getValue(Const.CURRENT_LATITUDE,"0"));
						
				// ADD PARAMS_LATITUDE
				mArrayParams.add(mObj$Params);

				mObj$Params = new JSONParams();
				mObj$Params.setStr$Key(Const.PARAMS_LONGITUDE);
				mObj$Params.setStr$value(Pref.getValue(Const.CURRENT_LONGITUDE,
						"0"));

				// ADD PARAMS_LONGITUDE
				mArrayParams.add(mObj$Params);
				
				
				// defaultHttpClient
				HttpParams mHttpParameters = new BasicHttpParams();
				// Set the timeout in milliseconds until a connection is established.
				int timeoutConnection = 8000;
				HttpConnectionParams.setConnectionTimeout(mHttpParameters, timeoutConnection);
				int timeoutSocket = 8000;
				HttpConnectionParams.setSoTimeout(mHttpParameters, timeoutSocket);
				
				DefaultHttpClient httpClient = new DefaultHttpClient(mHttpParameters);
				HttpPost httpPost = new HttpPost(Const.OPERATION_ADD_LOCATION);
				httpPost.setHeader("Content-Type", "application/json");
	
				JSONObject mJSONObject = new JSONObject();
				if (mArrayParams != null) {
					for (int y = 0; y < mArrayParams.size(); y++) {
						JSONParams mobj$Params = mArrayParams.get(y);
						if(y ==0){
							mJSONObject.put(mobj$Params.getStr$Key(),Integer.parseInt(mobj$Params.getStr$value()));
						}else{
							mJSONObject.put(mobj$Params.getStr$Key(),mobj$Params.getStr$value());	
						}
							
					}
				}
				
				Log.debug(TAG,"[ location ]" + mJSONObject.toString());
				StringEntity se = new StringEntity(mJSONObject.toString());
				se.setContentEncoding("UTF-8");
				se.setContentType("application/json");

				httpPost.setEntity(se);

				HttpResponse httpResponse = httpClient.execute(httpPost);
				HttpEntity httpEntity = httpResponse.getEntity();
				is = httpEntity.getContent();

				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is, "iso-8859-1"), 8);
				StringBuilder sb = new StringBuilder();
				String line = null;
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();
				json = sb.toString();

				mobj$Json = new JSONObject(json);

				String mLat = mobj$Json.getString("lat");
				String mLong = mobj$Json.getString("lng");
				Log.debug(TAG, "[ RESULT LAT ]" + mLat);
				Log.debug(TAG, "[ RESULT LOng ]" + mLong);
				
				result = true;
				temp = true;

			} catch (Exception e) {
				e.printStackTrace();
				result = true;
				return temp;
			}

			return temp;
		}

		@Override
		protected void onProgressUpdate(String... values) {
			Log.debug(TAG, "[  Progress Value ] " + values[0]);
			progressBar_Upload.setProgress(Integer.parseInt(values[0]));
		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			if(result == false){
				
				Toast.makeText(getApplicationContext(),"connection time out please try agin !!",1000*1).show();
			}
			setUploadView("2",result);
		}
	}

	/**
	 * UPLOAD IMAGE OVER SERVER
	 * 
	 * @author BHAVDIP
	 * 
	 */
	private class UploadImageTask extends AsyncTask<String, String, Boolean> {
		
		boolean temp = false;
		boolean result = false;
		int mProgressStatus = 0;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			result = false;
		}

		@Override
		protected Boolean doInBackground(String... params) {
				
			new Thread(new Runnable() {
	             public void run() {
	                 while (!result) {
	                	 
	                	 mProgressStatus = mProgressStatus + 1;
	                	 if(mProgressStatus < 100){
	                		 try {
								Thread.sleep(110);
							} catch (InterruptedException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
	                		 publishProgress(String.valueOf(mProgressStatus));
	                	 }
	                 
	                 }
	                 
	                 if(result){
	                	 publishProgress(String.valueOf(100)); 
	                 }
	             }
	         }).start();
			
			try{
				
				InputStream is = null;
				String result_image = "";

				ArrayList<JSONParams> mArrayParams;
				JSONParams mObj$Params;
				
				mArrayParams = new ArrayList<JSONParams>();
		        
				mObj$Params = new JSONParams();
				mObj$Params.setStr$Key(Const.PARAMS_RETRY);
		        mObj$Params.setStr$value(params[0]);		
		        mArrayParams.add(mObj$Params);
				
				mObj$Params = new JSONParams();
				mObj$Params.setStr$Key(Const.PARAMS_TYPE);
		        mObj$Params.setStr$value("Image");
		        mArrayParams.add(mObj$Params);
		        
		        mObj$Params = new JSONParams();
		        mObj$Params.setStr$Key(Const.PARAMS_CONTENT);
		        mObj$Params.setStr$value(params[1]);
		        mArrayParams.add(mObj$Params);
		        
		        
		     // defaultHttpClient
		        HttpParams mHttpParameters = new BasicHttpParams();
				// Set the timeout in milliseconds until a connection is established.
				int timeoutConnection = 3000;
				HttpConnectionParams.setConnectionTimeout(mHttpParameters, timeoutConnection);
				int timeoutSocket = 3000;
				HttpConnectionParams.setSoTimeout(mHttpParameters, timeoutSocket);
			
		        
				DefaultHttpClient httpClient = new DefaultHttpClient(mHttpParameters);
				HttpPost httpPost = new HttpPost(Const.OPERATION_ADD_FILE);
				httpPost.setHeader( "Content-Type", "application/json" );
				
				JSONObject mJSONObject = new JSONObject();    
				if(mArrayParams != null){
					
					for(int y=0;y<mArrayParams.size();y++){
						
						JSONParams mobj$Params = mArrayParams.get(y);
						if(y ==0){
							mJSONObject.put(mobj$Params.getStr$Key(),Integer.parseInt(mobj$Params.getStr$value()));
						}else{
							mJSONObject.put(mobj$Params.getStr$Key(),mobj$Params.getStr$value());	
						}
						
					}
				}
				
				Log.debug(TAG,"[ Image ]" + mJSONObject.toString());
				
				StringEntity se = new StringEntity(mJSONObject.toString());
				se.setContentEncoding("UTF-8");
			    se.setContentType("application/json");
			    
			    httpPost.setEntity(se); 
				
				HttpResponse httpResponse = httpClient.execute(httpPost);
				HttpEntity httpEntity = httpResponse.getEntity();
				is = httpEntity.getContent();
		        
				BufferedReader reader = new BufferedReader(new InputStreamReader(
						is, "iso-8859-1"), 8);
				StringBuilder sb = new StringBuilder();
				String line = null;
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();
				result_image = sb.toString();
				imageUploadFileNam = result_image.replaceAll("\"","").trim();
				result = true;
				temp =  true;
				
			}catch (Exception e) {
				e.printStackTrace();
				result = true;
				return temp;
			}
			return temp;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			setUploadView("1",result);
			
			
		}
		@Override
		protected void onProgressUpdate(String... values) {
			Log.debug(TAG, "[  Progress Value ] " + values[0]);
			progressBar_Upload.setProgress(Integer.parseInt(values[0]));
		}
	}
	
	
	/**
	 * UPLOAD AUDIO OVER SERVER
	 * 
	 * @author BHAVDIP
	 * 
	 */
	private class UploadAudioTask extends AsyncTask<String, String, Boolean> {
		
		boolean temp = false;
		boolean result = false;
		int mProgressStatus = 0;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			result = false;
		}

		@Override
		protected Boolean doInBackground(String... params) {
				
			new Thread(new Runnable() {
	             public void run() {
	                 while (!result) {
	                	 
	                	 mProgressStatus = mProgressStatus + 1;
	                	 if(mProgressStatus < 100){
	                		 try {
								Thread.sleep(110);
							} catch (InterruptedException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
	                		 publishProgress(String.valueOf(mProgressStatus));
	                	 }
	                 
	                 }
	                 
	                 if(result){
	                	 publishProgress(String.valueOf(100)); 
	                 }
	             }
	         }).start();
			
			try{
				
				InputStream is = null;
				String result_image = "";

				ArrayList<JSONParams> mArrayParams;
				JSONParams mObj$Params;
				
				mArrayParams = new ArrayList<JSONParams>();
		        
				
				mObj$Params = new JSONParams();
		        mObj$Params.setStr$Key(Const.PARAMS_RETRY);
		        mObj$Params.setStr$value(params[0]);
		        mArrayParams.add(mObj$Params);
				
				mObj$Params = new JSONParams();
		        mObj$Params.setStr$Key(Const.PARAMS_TYPE);
		        mObj$Params.setStr$value("Audio");
		        mArrayParams.add(mObj$Params);
		        
		        mObj$Params = new JSONParams();
		        mObj$Params.setStr$Key(Const.PARAMS_CONTENT);
		        mObj$Params.setStr$value(params[1]);
		        mArrayParams.add(mObj$Params);
		        
		        
		     // defaultHttpClient
		        HttpParams mHttpParameters = new BasicHttpParams();
				// Set the timeout in milliseconds until a connection is established.
				int timeoutConnection = 3000;
				HttpConnectionParams.setConnectionTimeout(mHttpParameters, timeoutConnection);
				int timeoutSocket = 3000;
				HttpConnectionParams.setSoTimeout(mHttpParameters, timeoutSocket);
		        
				DefaultHttpClient httpClient = new DefaultHttpClient(mHttpParameters);
				HttpPost httpPost = new HttpPost(Const.OPERATION_ADD_FILE);
				httpPost.setHeader( "Content-Type", "application/json" );
				
				JSONObject mJSONObject = new JSONObject();    
				if(mArrayParams != null){
					for(int y=0;y<mArrayParams.size();y++){
						
						JSONParams mobj$Params = mArrayParams.get(y);
						if(y == 0){
							mJSONObject.put(mobj$Params.getStr$Key(),Integer.parseInt(mobj$Params.getStr$value()));
						}else{
							mJSONObject.put(mobj$Params.getStr$Key(),mobj$Params.getStr$value());
						}
						
					}
				}
				
				Log.debug(TAG,"[ Audio ]" + mJSONObject.toString());
				
				StringEntity se = new StringEntity(mJSONObject.toString());
				se.setContentEncoding("UTF-8");
			    se.setContentType("application/json");
			    
			    httpPost.setEntity(se); 
				
				HttpResponse httpResponse = httpClient.execute(httpPost);
				HttpEntity httpEntity = httpResponse.getEntity();
				is = httpEntity.getContent();
		        
				BufferedReader reader = new BufferedReader(new InputStreamReader(
						is, "iso-8859-1"), 8);
				StringBuilder sb = new StringBuilder();
				String line = null;
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();
				result_image = sb.toString();
				audioUploadFileNam = result_image.replaceAll("\"","").trim();
				result = true;
				temp = true;
				
			}catch (Exception e) {
				e.printStackTrace();
				result = true;
				return temp;
			}
			
	        return temp;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			setUploadView("4",result);
		}
		@Override
		protected void onProgressUpdate(String... values) {
			Log.debug(TAG, "[  Progress Value ] " + values[0]);
			progressBar_Upload.setProgress(Integer.parseInt(values[0]));
		}
	}
	
	/**
	 * UPLOAD VIDEO OVER SERVER
	 * @author BHAVDIP
	 *
	 */
	
	private class UploadVideoTask extends AsyncTask<String, String, Boolean> {
		
		boolean temp = false;
		boolean result = false;
		int mProgressStatus = 0;
		String mVideoBase64;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			result = false;
		}

		@Override
		protected Boolean doInBackground(String... params) {
			
				new Thread(new Runnable() {
		             public void run() {
		                 while (!result) {
		                	 
		                	 mProgressStatus = mProgressStatus + 1;
		                	 if(mProgressStatus < 100){
		                		 try {
									Thread.sleep(1000);
								} catch (InterruptedException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
		                		 publishProgress(String.valueOf(mProgressStatus));
		                	 }
		                 
		                 }
		                 
		                 if(result){
		                	 publishProgress(String.valueOf(100)); 
		                 }
		             }
		         }).start();
			
			try{
				
				Thread mThread = new Thread(new  Runnable() {
					
					@Override
					public void run() {
						
						try {
							mVideoBase64  = Utility.convertBinaryToString(new FileInputStream(getRealPathFromURI(fileUri)));
						
						} catch (FileNotFoundException e) {
							e.printStackTrace();
						}
					}
				});
				mThread.start();
				
				mThread.join();
				
				InputStream is = null;
				String result_image = "";

				ArrayList<JSONParams> mArrayParams;
				JSONParams mObj$Params;
				
				mArrayParams = new ArrayList<JSONParams>();
		        
				mObj$Params = new JSONParams();
		        mObj$Params.setStr$Key(Const.PARAMS_RETRY);
		        mObj$Params.setStr$value(params[0]);
		        mArrayParams.add(mObj$Params);
				
				mObj$Params = new JSONParams();
		        mObj$Params.setStr$Key(Const.PARAMS_TYPE);
		        mObj$Params.setStr$value("Video");
		        mArrayParams.add(mObj$Params);
		        
		        mObj$Params = new JSONParams();
		        mObj$Params.setStr$Key(Const.PARAMS_CONTENT);
		        mObj$Params.setStr$value(mVideoBase64);
		        mArrayParams.add(mObj$Params);
		        
		        
		     // defaultHttpClient
		       DefaultHttpClient httpClient = new DefaultHttpClient();
		       HttpPost httpPost = new HttpPost(Const.OPERATION_ADD_FILE);
			   httpPost.setHeader( "Content-Type", "application/json" );
				
				JSONObject mJSONObject = new JSONObject();    
				if(mArrayParams != null){
					for(int y=0;y<mArrayParams.size();y++){
						JSONParams mobj$Params = mArrayParams.get(y);
						if (y == 0) {
							mJSONObject.put(mobj$Params.getStr$Key(),Integer.parseInt(mobj$Params.getStr$value()));
						}else{
							mJSONObject.put(mobj$Params.getStr$Key(),mobj$Params.getStr$value());	
						}
						
					}
				}
				

				Log.debug(TAG,"[ Video ]" + mJSONObject.toString());
				
				StringEntity se = new StringEntity(mJSONObject.toString());
				se.setContentEncoding("UTF-8");
			    se.setContentType("application/json");
			    
			    httpPost.setEntity(se); 
				
				HttpResponse httpResponse = httpClient.execute(httpPost);
				HttpEntity httpEntity = httpResponse.getEntity();
				is = httpEntity.getContent();
		        
				BufferedReader reader = new BufferedReader(new InputStreamReader(
						is, "iso-8859-1"), 8);
				StringBuilder sb = new StringBuilder();
				String line = null;
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();
				result_image = sb.toString();
				
				Log.debug(TAG,"[****** RESULT ******* ]" + result_image.replaceAll("\"","").trim());
				
				if(result_image != null && result_image.length() > 0){
					
					result = true;
					temp = true;	
				}else{
					
					result = true;
					temp = false;
					
				}
				
				
			}catch (Exception e) {
				e.printStackTrace();
				result = true;
				return temp;
			}
			
	        return temp;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			setUploadView("3",result);
		}
		@Override
		protected void onProgressUpdate(String... values) {
			Log.debug(TAG, "[  Progress Value ] " + values[0]);
			progressBar_Upload.setProgress(Integer.parseInt(values[0]));
		}
	}
	
	
	public void setUploadView(final String tag,final boolean flag) {

		runOnUiThread(new Runnable() {

			@Override
			public void run() {
					
					if(flag){
						
						imageview_feedback_ok.setVisibility(View.VISIBLE);
						btn_View.setVisibility(View.VISIBLE);
						btn_View.setTag(tag);	
					}else{
						
						btn_resend.setVisibility(View.VISIBLE);
						btn_resend.setTag(tag);
					}
			}
		});
	}

	public void cleanUploadView() {
		runOnUiThread(new Runnable() {

			@Override
			public void run() {

				imageview_feedback_ok.setVisibility(View.INVISIBLE);
				btn_View.setVisibility(View.INVISIBLE);
				btn_resend.setVisibility(View.INVISIBLE);
				progressBar_Upload.setProgress(0);
			}
		});

	}
	
	/**
	 * 
	 * @param request_code
	 * @param typeIntent like image/* , video/*
	 */
	public void openCustomIntent(int request_code,String typeIntent){
		
		Intent captureIntent = null;
		// Camera.
	    final List<Intent> cameraIntents = new ArrayList<Intent>();
	    if(typeIntent.equalsIgnoreCase("image/*")){
	    	captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);	
	    }else if(typeIntent.equalsIgnoreCase("video/*")){
	    	captureIntent = new Intent(android.provider.MediaStore.ACTION_VIDEO_CAPTURE);
	    }
	    
	    final PackageManager packageManager = getPackageManager();
	    final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
	    
	    for(ResolveInfo res : listCam) {
	    	
	        final String packageName = res.activityInfo.packageName;
	        final Intent intent = new Intent(captureIntent);
	        intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
	        intent.setPackage(packageName);
	        cameraIntents.add(intent);
	    }

	    // Filesystem.
	    final Intent galleryIntent = new Intent();
	    galleryIntent.setType(typeIntent);
	    galleryIntent.setAction(Intent.ACTION_GET_CONTENT);

	    final Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Source");
	    chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[]{}));
	    startActivityForResult(chooserIntent, request_code);
	}
}
